package com.chengxusheji.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.chengxusheji.utils.ExportExcelUtil;
import com.chengxusheji.dao.CardGetRecordDAO;
import com.chengxusheji.dao.MemberCardDAO;
import com.chengxusheji.dao.MemberInfoDAO;
import com.chengxusheji.domain.BusinessCompany;
import com.chengxusheji.domain.CardGetRecord;
import com.chengxusheji.domain.MemberCard;
import com.chengxusheji.domain.MemberInfo;
@Controller @Scope("prototype")
public class MemberInfoAction extends ActionSupport {

/*图片字段grzp参数接收*/
	 private File grzpFile;
	 private String grzpFileFileName;
	 private String grzpFileContentType;
	 public File getGrzpFile() {
		return grzpFile;
	}
	public void setGrzpFile(File grzpFile) {
		this.grzpFile = grzpFile;
	}
	public String getGrzpFileFileName() {
		return grzpFileFileName;
	}
	public void setGrzpFileFileName(String grzpFileFileName) {
		this.grzpFileFileName = grzpFileFileName;
	}
	public String getGrzpFileContentType() {
		return grzpFileContentType;
	}
	public void setGrzpFileContentType(String grzpFileContentType) {
		this.grzpFileContentType = grzpFileContentType;
	}
    /*界面层需要查询的属性: 会员账号*/
    private String hyzh;
    public void setHyzh(String hyzh) {
        this.hyzh = hyzh;
    }
    public String getHyzh() {
        return this.hyzh;
    }

    /*界面层需要查询的属性: 姓名*/
    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }

    /*界面层需要查询的属性: 出生日期*/
    private String birthday;
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    public String getBirthday() {
        return this.birthday;
    }

    /*界面层需要查询的属性: 身份证号*/
    private String sfzh;
    public void setSfzh(String sfzh) {
        this.sfzh = sfzh;
    }
    public String getSfzh() {
        return this.sfzh;
    }

    /*界面层需要查询的属性: 联系电话*/
    private String lxdh;
    public void setLxdh(String lxdh) {
        this.lxdh = lxdh;
    }
    public String getLxdh() {
        return this.lxdh;
    }

    /*当前第几页*/
    private int currentPage;
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getCurrentPage() {
        return currentPage;
    }

    /*一共多少页*/
    private int totalPage;
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    public int getTotalPage() {
        return totalPage;
    }

    /*当前查询的总记录数目*/
    private int recordNumber;
    public void setRecordNumber(int recordNumber) {
        this.recordNumber = recordNumber;
    }
    public int getRecordNumber() {
        return recordNumber;
    }

    /*业务层对象*/
    @Resource MemberInfoDAO memberInfoDAO;
    @Resource MemberCardDAO memberCardDAO;
    @Resource CardGetRecordDAO cardGetRecordDAO;

    /*待操作的MemberInfo对象*/
    private MemberInfo memberInfo;
    public void setMemberInfo(MemberInfo memberInfo) {
        this.memberInfo = memberInfo;
    }
    public MemberInfo getMemberInfo() {
        return this.memberInfo;
    }

    /*跳转到添加MemberInfo视图*/
    public String AddView() {
        ActionContext ctx = ActionContext.getContext();
        return "add_view";
    }

    /*添加MemberInfo信息*/
    @SuppressWarnings("deprecation")
    public String AddMemberInfo() {
        ActionContext ctx = ActionContext.getContext();
        /*验证会员账号是否已经存在*/
        String hyzh = memberInfo.getHyzh();
        MemberInfo db_memberInfo = memberInfoDAO.GetMemberInfoByHyzh(hyzh);
        if(null != db_memberInfo) {
            ctx.put("error",  java.net.URLEncoder.encode("该会员账号已经存在!"));
            return "error";
        }
        try {
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String grzpFileName = ""; 
       	 	if(grzpFile != null) {
       	 		InputStream is = new FileInputStream(grzpFile);
       			String fileContentType = this.getGrzpFileContentType();
       			if(fileContentType.equals("image/jpeg")  || fileContentType.equals("image/pjpeg"))
       				grzpFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				grzpFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				ctx.put("error",  java.net.URLEncoder.encode("上传图片格式不正确!"));
       				return "error";
       			}
       			File file = new File(path, grzpFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
       	 	}
            if(grzpFile != null)
            	memberInfo.setGrzp("upload/" + grzpFileName);
            else
            	memberInfo.setGrzp("upload/NoImage.jpg");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            memberInfo.setAddTime(sdf.format(new java.util.Date()));
            
            memberInfoDAO.AddMemberInfo(memberInfo);
            ctx.put("message",  java.net.URLEncoder.encode("会员添加成功!"));
            return "add_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("会员添加失败!"));
            return "error";
        }
    }

    /*查询MemberInfo信息*/
    public String QueryMemberInfo() {
        if(currentPage == 0) currentPage = 1;
        if(hyzh == null) hyzh = "";
        if(name == null) name = "";
        if(birthday == null) birthday = "";
        if(sfzh == null) sfzh = "";
        if(lxdh == null) lxdh = "";
        List<MemberInfo> memberInfoList = memberInfoDAO.QueryMemberInfoInfo(hyzh, name, birthday, sfzh, lxdh, currentPage);
        /*计算总的页数和总的记录数*/
        memberInfoDAO.CalculateTotalPageAndRecordNumber(hyzh, name, birthday, sfzh, lxdh);
        /*获取到总的页码数目*/
        totalPage = memberInfoDAO.getTotalPage();
        /*当前查询条件下总记录数*/
        recordNumber = memberInfoDAO.getRecordNumber();
        ActionContext ctx = ActionContext.getContext();
        ctx.put("memberInfoList",  memberInfoList);
        ctx.put("totalPage", totalPage);
        ctx.put("recordNumber", recordNumber);
        ctx.put("currentPage", currentPage);
        ctx.put("hyzh", hyzh);
        ctx.put("name", name);
        ctx.put("birthday", birthday);
        ctx.put("sfzh", sfzh);
        ctx.put("lxdh", lxdh);
        return "query_view";
    }
    
    

    /*商家登陆查询本商家MemberInfo信息*/
    public String QueryMyMemberInfo() {
    	
    	ActionContext ctx = ActionContext.getContext(); 
    	String sjad = (String)ctx.getSession().get("username");
    	
    	BusinessCompany companyObj = new BusinessCompany();
    	companyObj.setSjad(sjad);
    	
    	ArrayList<MemberCard> memberCardList = memberCardDAO.QueryMemberCardInfo("", companyObj, null, null);
    	 
    	List<MemberInfo> memberInfoList = new ArrayList<MemberInfo>();
    	
    	for(MemberCard memberCard:memberCardList) {
    		ArrayList<CardGetRecord> cardGetRecordList = cardGetRecordDAO.QueryCardGetRecordInfo(null, memberCard);
    		for(CardGetRecord cardGetRecord: cardGetRecordList) {
    			memberInfoList.add(cardGetRecord.getMemberObj());
    		}
    	}
    	
        if(currentPage == 0) currentPage = 1;
        if(hyzh == null) hyzh = "";
        if(name == null) name = "";
        if(birthday == null) birthday = "";
        if(sfzh == null) sfzh = "";
        if(lxdh == null) lxdh = "";
        
        ctx.put("memberInfoList",  memberInfoList);
        
        return "company_query_view";
    }

    /*后台导出到excel*/
    public String QueryMemberInfoOutputToExcel() { 
        if(hyzh == null) hyzh = "";
        if(name == null) name = "";
        if(birthday == null) birthday = "";
        if(sfzh == null) sfzh = "";
        if(lxdh == null) lxdh = "";
        List<MemberInfo> memberInfoList = memberInfoDAO.QueryMemberInfoInfo(hyzh,name,birthday,sfzh,lxdh);
        ExportExcelUtil ex = new ExportExcelUtil();
        String title = "MemberInfo信息记录"; 
        String[] headers = { "会员账号","姓名","性别","出生日期","身份证号","籍贯","联系电话","个人照片","地址","账号状态"};
        List<String[]> dataset = new ArrayList<String[]>(); 
        for(int i=0;i<memberInfoList.size();i++) {
        	MemberInfo memberInfo = memberInfoList.get(i); 
        	dataset.add(new String[]{memberInfo.getHyzh(),memberInfo.getName(),memberInfo.getSex(),memberInfo.getBirthday(),memberInfo.getSfzh(),memberInfo.getJg(),memberInfo.getLxdh(),memberInfo.getGrzp(),memberInfo.getDz(),memberInfo.getZhzt() + ""});
        }
        /*
        OutputStream out = null;
		try {
			out = new FileOutputStream("C://output.xls");
			ex.exportExcel(title,headers, dataset, out);
		    out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
		HttpServletResponse response = null;//创建一个HttpServletResponse对象 
		OutputStream out = null;//创建一个输出流对象 
		try { 
			response = ServletActionContext.getResponse();//初始化HttpServletResponse对象 
			out = response.getOutputStream();//
			response.setHeader("Content-disposition","attachment; filename="+"MemberInfo.xls");//filename是下载的xls的名，建议最好用英文 
			response.setContentType("application/msexcel;charset=UTF-8");//设置类型 
			response.setHeader("Pragma","No-cache");//设置头 
			response.setHeader("Cache-Control","no-cache");//设置头 
			response.setDateHeader("Expires", 0);//设置日期头  
			String rootPath = ServletActionContext.getServletContext().getRealPath("/");
			ex.exportExcel(rootPath,title,headers, dataset, out);
			out.flush();
		} catch (IOException e) { 
			e.printStackTrace(); 
		}finally{
			try{
				if(out!=null){ 
					out.close(); 
				}
			}catch(IOException e){ 
				e.printStackTrace(); 
			} 
		}
		return null;
    }
    /*前台查询MemberInfo信息*/
    public String FrontQueryMemberInfo() {
        if(currentPage == 0) currentPage = 1;
        if(hyzh == null) hyzh = "";
        if(name == null) name = "";
        if(birthday == null) birthday = "";
        if(sfzh == null) sfzh = "";
        if(lxdh == null) lxdh = "";
        List<MemberInfo> memberInfoList = memberInfoDAO.QueryMemberInfoInfo(hyzh, name, birthday, sfzh, lxdh, currentPage);
        /*计算总的页数和总的记录数*/
        memberInfoDAO.CalculateTotalPageAndRecordNumber(hyzh, name, birthday, sfzh, lxdh);
        /*获取到总的页码数目*/
        totalPage = memberInfoDAO.getTotalPage();
        /*当前查询条件下总记录数*/
        recordNumber = memberInfoDAO.getRecordNumber();
        ActionContext ctx = ActionContext.getContext();
        ctx.put("memberInfoList",  memberInfoList);
        ctx.put("totalPage", totalPage);
        ctx.put("recordNumber", recordNumber);
        ctx.put("currentPage", currentPage);
        ctx.put("hyzh", hyzh);
        ctx.put("name", name);
        ctx.put("birthday", birthday);
        ctx.put("sfzh", sfzh);
        ctx.put("lxdh", lxdh);
        return "front_query_view";
    }

    /*查询要修改的MemberInfo信息*/
    public String ModifyMemberInfoQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键hyzh获取MemberInfo对象*/
        MemberInfo memberInfo = memberInfoDAO.GetMemberInfoByHyzh(hyzh);

        ctx.put("memberInfo",  memberInfo);
        return "modify_view";
    }

    /*查询要修改的MemberInfo信息*/
    public String FrontShowMemberInfoQuery() {
        ActionContext ctx = ActionContext.getContext();
        /*根据主键hyzh获取MemberInfo对象*/
        MemberInfo memberInfo = memberInfoDAO.GetMemberInfoByHyzh(hyzh);

        ctx.put("memberInfo",  memberInfo);
        return "front_show_view";
    }

    /*更新修改MemberInfo信息*/
    public String ModifyMemberInfo() {
        ActionContext ctx = ActionContext.getContext();
        try {
            String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
            /*处理图片上传*/
            String grzpFileName = ""; 
       	 	if(grzpFile != null) {
       	 		InputStream is = new FileInputStream(grzpFile);
       			String fileContentType = this.getGrzpFileContentType();
       			if(fileContentType.equals("image/jpeg") || fileContentType.equals("image/pjpeg"))
       				grzpFileName = UUID.randomUUID().toString() +  ".jpg";
       			else if(fileContentType.equals("image/gif"))
       				grzpFileName = UUID.randomUUID().toString() +  ".gif";
       			else {
       				ctx.put("error",  java.net.URLEncoder.encode("上传图片格式不正确!"));
       				return "error";
       			}
       			File file = new File(path, grzpFileName);
       			OutputStream os = new FileOutputStream(file);
       			byte[] b = new byte[1024];
       			int bs = 0;
       			while ((bs = is.read(b)) > 0) {
       				os.write(b, 0, bs);
       			}
       			is.close();
       			os.close();
            memberInfo.setGrzp("upload/" + grzpFileName);
       	 	}
            memberInfoDAO.UpdateMemberInfo(memberInfo);
            ctx.put("message",  java.net.URLEncoder.encode("MemberInfo信息更新成功!"));
            return "modify_success";
        } catch (Exception e) {
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("MemberInfo信息更新失败!"));
            return "error";
       }
   }

    /*删除MemberInfo信息*/
    public String DeleteMemberInfo() {
        ActionContext ctx = ActionContext.getContext();
        try { 
            memberInfoDAO.DeleteMemberInfo(hyzh);
            ctx.put("message",  java.net.URLEncoder.encode("MemberInfo删除成功!"));
            return "delete_success";
        } catch (Exception e) { 
            e.printStackTrace();
            ctx.put("error",  java.net.URLEncoder.encode("MemberInfo删除失败!"));
            return "error";
        }
    }

}
